#include "RecursiveMutex.h"

DEF_BEG_LIBTOOLS

CRecursiveMutex::CRecursiveMutex()
{
	 _lockCount = 0;
	 _lockThreadId = 0;
}

CRecursiveMutex::~CRecursiveMutex()
{
	 _lockCount = 0;
	 _lockThreadId = 0;
}

void CRecursiveMutex::Lock()
{
	long curThreadId = ShareApi::GetCurrentThreadId();
	if (!Test_Recursive(curThreadId))
	{
		 _mutex.Lock();
		ShareApi::InterlockedExchange(&_lockThreadId, curThreadId);
		 _lockCount = 1;
	}
}

void CRecursiveMutex::Unlock()
{
	if (!--_lockCount)
	{
		ShareApi::InterlockedExchange(&_lockThreadId, 0);
		 _mutex.Unlock();
	}
}

SYNCHANDLE CRecursiveMutex::Handle()
{
	return _mutex.Handle();
}

bool CRecursiveMutex::Test_Recursive(long curThreadId)
{
	if(ShareApi::InterlockedExchangeAdd(&_lockThreadId, 0) == curThreadId)
	{
		return true;
	}

	return false;
}

DEF_END_LIBTOOLS